package edu.langnan.xiaoli.config.security.handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import edu.langnan.xiaoli.base.AjaxResult;
import edu.langnan.xiaoli.config.security.LoginUser;
import edu.langnan.xiaoli.config.security.TokenService;
import edu.langnan.xiaoli.constant.HttpStatus;
import edu.langnan.xiaoli.utils.ServletUtils;
import edu.langnan.xiaoli.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cql
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {


    private static final Logger log = LoggerFactory.getLogger(LogoutSuccessHandlerImpl.class);

    @Autowired
    private TokenService tokenService;


    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        ServletUtils.renderString(response, new ObjectMapper()
                .writeValueAsString(
                        AjaxResult.error(
                                HttpStatus.OK.getCode(),
                                "退出成功")));
    }
}

